﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace System.Linq
{
  public static class IEnumerableExtensions
  {
    public static IEnumerable<T> CopyOf<T>(this IEnumerable<T> list)
    {
      List<T> copy = new List<T>(list);
      foreach (T item in list.ToList())
        yield return item;
    }

    public static IEnumerable<T> Sync<T>(this IEnumerable<T> list, ReaderWriterLockSlim sync)
    {
      List<T> l = null;
      using (new SafeReaderLock(sync))
        l = new List<T>(list.CopyOf());

      foreach (T item in l)
        yield return item;
    }

    public static IEnumerable<T> Sync<T>(this IEnumerable<T> list, object sync)
    {
      List<T> l = null;
      using (new SafeLock(sync))
        l = new List<T>(list.CopyOf());

      foreach (T item in l)
        yield return item;
    }

    public static int IndexOf<T>(this IEnumerable<T> list, T target)
    {
      int index = 0;

      foreach (T item in list)
        if (item.Equals(target))
          return index;
        else
          index++;

      return -1;
    }
  }
}
